package cn.bytecollege.controller;


import cn.bytecollege.model.User;
import cn.bytecollege.model.UserAddress;
import cn.bytecollege.model.UserDetail;
import cn.bytecollege.service.FileUploadService;
import cn.bytecollege.service.PersonalService;
import cn.bytecollege.vo.PersonalVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@Controller
public class PersonalController {

    String FILEPATH = "/src/main/resources/static/images/userImage";



    private UserDetail defaultUserDetail = new UserDetail();
    private UserAddress defaultUserAddress = new UserAddress();
    @Autowired
    private PersonalService personalService;

    @Autowired
    private FileUploadService fileUploadService;


    @RequestMapping("/toUserDetail")
    public String toUserDetail(HttpSession session,
                               Model model) {
        User user = (User) session.getAttribute("user");

        UserAddress userAddress = personalService.getUserAddressByUserId(user.getUserId());
        UserDetail userDetail = personalService.getUserDetailByUserId(user.getUserId());

        if (userDetail == null) {
            defaultUserDetail.setUserImage("/images/userImage/defaultImage.jfif");
            defaultUserDetail.setUserGender("未知");
            userDetail = defaultUserDetail;
        }
        if (userAddress == null) {
            defaultUserAddress.setTelephone("188****8888");
            defaultUserAddress.setRealName("***");
            defaultUserAddress.setAddress("**楼**单元***");
            userAddress = defaultUserAddress;
        }

        PersonalVO personalVO = new PersonalVO(user, userAddress, userDetail);

        model.addAttribute("personal", personalVO);
        return "pPersionInfor";
    }

    @RequestMapping("/toHeadPhoto")
    public String toHeadPhoto() {
        return "fileUpload";
    }

    @RequestMapping("/addHeadPhoto")
    public String addHeadPhoto(HttpSession session,
                               MultipartFile file) {

        User user = (User) session.getAttribute("user");

        Integer userId = user.getUserId();
        fileUploadService.fileUpload(FILEPATH, file, userId);
        return "redirect:/toUserDetail";
    }

    @RequestMapping("/modGender")
    @Transactional
    public String modRealNameAndGender(HttpSession session,
                                       String gender) {
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        UserDetail userDetail = UserDetail.builder().userId(userId).userGender(gender).build();
        personalService.modUserDetailByUserId(userDetail);
        return "redirect:/toUserDetail";
    }
}
